﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;

namespace SpringBeansEditor.GUIHelpers
{
    /// <summary>
    /// Allows the user to load and save a Spring XML objects definition
    /// </summary>
    public partial class LoadXML : UserControl
    {
        public XmlDataProvider DataXml { get; set; }

        public LoadXML()
        {
            InitializeComponent();
        }

        private void BrowseXMLFileBtn_Click(object sender, RoutedEventArgs e)
        {

            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            //dlg.FileName = "Spring XML file";
            //dlg.DefaultExt = ".xml"; // Default file extension
            //dlg.Filter = "Spring XML (.xml)|*.xml"; // Filter files by extension
            //dlg.a

            // Show open file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Opens the XML file chosen in the file dialog
            if (result == true)
            {
                XmlToLoadTxt.Text = dlg.FileName;
                DataXml.Source = new Uri(XmlToLoadTxt.Text);
            }
        }

        private void LoadXmlBtn_Click(object sender, RoutedEventArgs e)
        {
            DataXml.Source = new Uri(XmlToLoadTxt.Text);

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DataXml.Document.Save(DataXml.Source.LocalPath);
        }

        private void NewXMLBtn_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = "applicationContext.xml";
            dlg.DefaultExt = ".xml"; // Default file extension
            dlg.Filter = "Spring XML (.xml)|*.xml"; // Filter files by extension

            // Show open file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Opens the XML file chosen in the file dialog
            if (result == true)
            {
                XmlToLoadTxt.Text = dlg.FileName;
                XmlTextWriter xmlWriter = new XmlTextWriter(XmlToLoadTxt.Text, System.Text.Encoding.UTF8);
                xmlWriter.Formatting = Formatting.Indented;
                xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
                xmlWriter.WriteStartElement("objects","http://www.springframework.net"); 
                xmlWriter.Close();

                DataXml.Source = new Uri(XmlToLoadTxt.Text);
            }

        }
    }
}
